package larrys.pomodoro.controller.ajax;

import java.util.Locale;

import larrys.pomodoro.Constant;
import larrys.pomodoro.domain.entity.PomodoroUser;
import larrys.pomodoro.domain.exception.PomodoroException;
import larrys.pomodoro.domain.service.RoundService;
import larrys.pomodoro.util.AjaxResponseUtil;
import larrys.pomodoro.util.SecurityUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RoundAjaxController {

	private static Log logger = LogFactory.getLog(RoundAjaxController.class);

	@Autowired
	private MessageSource messageSource;

	@Autowired
	private RoundService roundService;

	@ResponseBody
	@RequestMapping(value = "/startround", method = RequestMethod.GET)
	public String startRound(Model model, Locale locale) {
		PomodoroUser user = SecurityUtils.getCurrentUser();
		logger.debug("Trying to start running round for:" + user);
		try {
			roundService.startRound(user.getId());
		} catch (PomodoroException e) {
			String message = messageSource.getMessage(
					Constant.EXCEPTION_MSG_CODE_PRIFIX + e.getExceptionCode(),
					null, locale);
			return AjaxResponseUtil.buildFailureWithMsgResponse(message);			
		}
		return AjaxResponseUtil.buildSuccessResponse();
	}
}
